package com.feng.leetcode;

import java.util.Arrays;
import java.util.LinkedList;

/**
 * @author feng
 * @decrition
 * @date 2022/11/1422:26
 */
public class L805 {
    public static boolean splitArraySameAverage(int[] nums) {
        if (nums.length < 2) {
            return false;
        }
        Arrays.sort(nums);
        LinkedList<Integer> right = new LinkedList<>();
        LinkedList<Integer> left = new LinkedList<>();
        int sumRight = 0;
        int sumLeft = 0;
        for (int i = 0; i < nums.length; i++) {
            if (i % 2 == 0) {
                sumRight += nums[i];
                right.add(nums[i]);
            } else {
                sumLeft += nums[i];
                left.add(nums[i]);
            }
        }
        Double avgRight = (double) sumRight / right.size();
        Double avgLeft = (double) sumLeft / left.size();
        boolean result = true;
        int i = 0;
        while (avgLeft.compareTo(avgRight) != 0 && i < nums.length) {
            if (right.size() <= 1 || left.size() <= 1) {
                result = false;
                break;
            }
            if (avgLeft < avgRight) {
                Integer integer = right.removeLast();
                sumRight -= integer;
                sumLeft += integer;
                avgRight = (double) sumRight / right.size();
                avgLeft = (double) sumLeft / left.size();
                left.addFirst(integer);
            } else {
                Integer integer = left.removeLast();
                sumRight += integer;
                sumLeft -= integer;
                avgRight = (double) sumRight / right.size();
                avgLeft = (double) sumLeft / left.size();
                right.addFirst(integer);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[] nums = {1,2,3,4,5,6,7,8};
        System.out.println(splitArraySameAverage(nums));
    }
}
